package com.ruoyi.business.appuser.service.impl;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.business.appuser.service.WeiXinService;
import com.ruoyi.business.appuser.vo.*;
import com.zhhy.tool.utils.IntegerUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author Tellsea
 * @date 2021/05/20
 */
@Slf4j
@Service
public class WeiXinServiceImpl implements WeiXinService {

    @Autowired
    private WeiXinConfig weiXinConfig;

    @Override
    public Code2Session code2Session(String code) {
        String url = "https://api.weixin.qq.com/sns/jscode2session?" +
                "appid=" + weiXinConfig.getAppId() +
                "&secret=" + weiXinConfig.getSecret() +
                "&js_code=" + code +
                "&grant_type=authorization_code";
        String result = HttpUtil.get(url);
        JSONObject jsonObject = JSONObject.parseObject(result);
        Code2Session code2Session = new Code2Session().setOpenId(jsonObject.getString("openid"))
                .setSessionKey(jsonObject.getString("session_key"))
                .setUnionId(jsonObject.getString("unionid"))
                .setErrCode(jsonObject.getInteger("errcode"))
                .setErrMsg(jsonObject.getString("errmsg"));
        if (StringUtils.isEmpty(code2Session.getOpenId())) {
            code2Session.setErrMsg("OpenId为空");
        } else if (IntegerUtils.eq(code2Session.getErrCode(), -1)) {
            code2Session.setErrMsg("系统繁忙，此时请开发者稍候再试");
        } else if (IntegerUtils.eq(code2Session.getErrCode(), 40029)) {
            code2Session.setErrMsg("code 无效");
        } else if (IntegerUtils.eq(code2Session.getErrCode(), 45011)) {
            code2Session.setErrMsg("频率限制，每个用户每分钟100次");
        } else {
            code2Session.setErrMsg("其他错误");
        }
        return code2Session;
    }

    @Override
    public AccessToken getAccessToken() {
        String url = "https://api.weixin.qq.com/cgi-bin/token?" +
                "grant_type=client_credential" +
                "&appid=" + weiXinConfig.getAppId() +
                "&secret=" + weiXinConfig.getSecret();
        String result = HttpUtil.get(url);
        JSONObject jsonObject = JSONObject.parseObject(result);
        AccessToken accessToken = new AccessToken().setAccessToken(jsonObject.getString("access_token"))
                .setExpiresIn(jsonObject.getInteger("expires_in"))
                .setErrCode(jsonObject.getInteger("errcode"))
                .setErrMsg(jsonObject.getString("errmsg"));
        if (StringUtils.isEmpty(accessToken.getAccessToken())) {
        } else if (IntegerUtils.eq(accessToken.getErrCode(), -1)) {
            accessToken.setErrMsg("系统繁忙，此时请开发者稍候再试");
        } else if (IntegerUtils.eq(accessToken.getErrCode(), 40001)) {
            accessToken.setErrMsg("AppSecret 错误或者 AppSecret 不属于这个小程序，请开发者确认 AppSecret 的正确性");
        } else if (IntegerUtils.eq(accessToken.getErrCode(), 40002)) {
            accessToken.setErrMsg("请确保 grant_type 字段值为 client_credential");
        } else if (IntegerUtils.eq(accessToken.getErrCode(), 40013)) {
            accessToken.setErrMsg("不合法的 AppID，请开发者检查 AppID 的正确性，避免异常字符，注意大小写");
        } else {
            accessToken.setErrMsg("其他错误");
        }
        return accessToken;
    }

    @Override
    public void sendTemplateMessage(String openId, String msg) {
        // 未测试
        String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + WeiXinToken.token;
        cn.hutool.json.JSONObject param = new cn.hutool.json.JSONObject();
        param.set("touser", "osD0e4-ZNjsEBc95T_NFQh0Y0zlM");
        param.set("template_id", TemplateId.order);
        param.set("page", "index");
        cn.hutool.json.JSONObject content = new cn.hutool.json.JSONObject();
        content.set("thing1", new cn.hutool.json.JSONObject().set("value", msg));
        content.set("thing2", new cn.hutool.json.JSONObject().set("value", "123456"));
        param.set("data", content);
        String result = HttpUtil.post(url, param.toString());
        System.out.println(result);
    }
}
